package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    //用户下单
    @Override
    @Transactional  //添加事务
    public void submit(Orders orders) {
        //获得用户id
        Long currentId = BaseContext.getCurrentId();

        //查询当前用户购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> list = shoppingCartService.list(lqw);

        //判断当前购物车是否有数据
        if (list == null || list.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }

        AtomicInteger amount = new AtomicInteger(0);

        //查询用户数据
        User byId = userService.getById(currentId);

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (byId == null){
            throw  new CustomException("用户地址信息有误，不能下单");
        }

        long id = IdWorker.getId();//生成一个订单号


        //遍历购物车数据
        List<OrderDetail> orderDetails = list.stream().map((itm)->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(itm,orderDetail);
            orderDetail.setOrderId(id);
            amount.addAndGet(itm.getAmount().multiply(new BigDecimal(itm.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        //向订单表插入数据
        orders.setNumber(String.valueOf(id));//设置订单号
        orders.setCheckoutTime(LocalDateTime.now());//设置完成时间
        orders.setOrderTime(LocalDateTime.now());//设置创建时间
        orders.setStatus(2);//设置订单状态
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(currentId);//设置用户id
        orders.setUserName(byId.getName());//设置用户姓名
        orders.setConsignee(addressBook.getConsignee());//设置收货人姓名
        orders.setPhone(addressBook.getPhone());//设置收货人电话
        //设置详细地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                         + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        this.save(orders);

        //向订单明细表插入数据（多条）
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(lqw);
    }
}
